package org.personal.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StatementSupport extends Statement{

	/** 构造方法
	 * @param connection 数据库连接对象
	 */
	public StatementSupport(Connection connection) {
		super(connection);
	}

	/** 更新数据
	 * @param sql SQL语句
	 * @return 影响行数
	 */
	public int update(String sql){
		int row=0;
		Connection con = null;
		java.sql.Statement stmt = null;
		try {
			con=getConnection();
			stmt =con.createStatement();
			row=stmt.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				if(stmt!=null)stmt.close();
				if(con!=null)con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return row;
	}
	
	/** 查询语句,返回仅第一行第一个字段值
	 * @param sql  SQL语句
	 * @return 一个对象
	 */
	public Object query(String sql){
		Object result=null;
		Connection con = null;
		java.sql.Statement stmt = null;
		ResultSet rs = null;
		try {
			con=getConnection();
			stmt =con.createStatement();
			rs=stmt.executeQuery(sql);
			if(rs.next())result=rs.getObject(1);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				if(rs!=null)rs.close();
				if(stmt!=null)stmt.close();
				if(con!=null)con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	/** 执行查询返回集合对象
	 * @param sql SQL语句
	 * @param rowMapper
	 * @return 查询的对象集合
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List query(String sql,RowMapper rowMapper){
		List resultList=new ArrayList();int rowNum=1;
		Connection con = null;
		java.sql.Statement stmt = null;
		ResultSet rs = null;
		try {
			con=getConnection();
			stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
			while(rs.next()) {
				resultList.add(rowMapper.mapRow(rs, rowNum));
				rowNum++;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				if(rs!=null)rs.close();
				if(stmt!=null)stmt.close();
				if(con!=null)con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return resultList;
	}
}
